﻿namespace WPForms.Phone.DataAccess
{
    using System;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Ink;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;

    /// <summary>
    /// Data access helper for sql ce
    /// </summary>
    public class SqlCeDataAccess : IDataAccess
    {
        /// <summary>
        /// The connection string.
        /// </summary>
        private string connectionString;

        /// <summary>
        /// Initializes a new instance of the <see cref="SqlCeDataAccess"/> class.
        /// </summary>
        /// <param name="connectionString">The connection string.</param>
        public SqlCeDataAccess(string connectionString)
        {
            this.connectionString = connectionString;
            this.InSession(
                dc =>
                {
                    if (!dc.DatabaseExists())
                    {
                        dc.CreateDatabase();
                    }
                });
        }

        /// <summary>
        /// Executes the given action in a database session. Changes won't be saved.
        /// </summary>
        /// <param name="action">The action to execute.</param>
        public void InSession(Action<WPFormsDataContext> action)
        {
            using (var dc = new WPFormsDataContext(this.connectionString))
            {
                action(dc);
            }
        }

        /// <summary>
        /// Executes the given action in a database transaction. Changes will be saved.
        /// </summary>
        /// <param name="action">The action to execute.</param>
        public void InTransaction(Action<WPFormsDataContext> action)
        {
            using (var dc = new WPFormsDataContext(this.connectionString))
            {
                action(dc);
                dc.SubmitChanges();
            }
        }
    }
}
